<template>
  <el-dialog
    class="material-add-plan-comp"
    :title="title"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    :visible="visible"
    :width="width"
    :before-close="handleCancel">
    <el-form
      element-loading-custom-class="custom-load"
      :model="ruleForm"
      :rules="rules"
      label-suffix="："
      size="medium"
      ref="ruleForm"
      :label-width="$setRem(140)"
      class="rule-form"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="计划名称" prop="planName" required>
            <span class="detail-text" v-if="hasDetail || hasCheck || hasFeedback || hasClose">{{ ruleForm.planName || '' }}</span>
            <el-input
              v-else
              type="text"
              clearable
              placeholder="请输入计划名称"
              v-model="ruleForm.planName">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计划编号" prop="planNo" required>
            <span class="detail-text" v-if="hasDetail || hasCheck || hasFeedback || hasClose">
              {{ ruleForm.planNo || '' }}
            </span>
            <el-input
              v-else
              disabled
              type="text"
              placeholder="请输入计划编号"
              clearable
              :value="ruleForm.planNo">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <div v-if="hasEdit || hasAdd" class="btns">
          <el-button
            class="add-btn"
            @click="handleAdd"
            type="primary"
            size="small"
            icon="el-icon-plus">新增</el-button>
          <el-button
            class="add-btn"
            @click="handleDelete"
            type="danger"
            size="small"
            icon="el-icon-delete">删除</el-button>
        </div>
        <el-table
          class="table-container"
          :data="tableData"
          element-loading-custom-class="custom-load"
          row-key="id">
          <el-table-column v-if="hasEdit || hasAdd" label="" width="60" align="center">
            <template slot-scope="scope">
              <el-checkbox :value="scope.row.hasCheck" @change="handleSelect(scope.row, scope['$index'])"></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column label="序号" type="index" width="60" align="center"></el-table-column>
          <el-table-column label="名称" prop="materialName" align="center"></el-table-column>
          <el-table-column label="规格/型号" prop="specs" align="center"></el-table-column>
          <el-table-column label="计划数量" prop="planNum" width="100" align="center"></el-table-column>
          <el-table-column v-if="hasFeedback" label="本次到场数量" prop="currentNum" width="120" align="center">
            <template slot-scope="scope">
              <input-name
                type="number"
                :min="0"
                :controls="false"
                emptyText="--"
                :text="scope.row.currentNum"
                :change="(v) => handleChange(v, scope.row, scope['$index'])">
              </input-name>
            </template>
          </el-table-column>
          <el-table-column v-if="hasFeedback || hasClose" label="累计到场数量" prop="totalNum" width="130" align="center"></el-table-column>
          <el-table-column label="单位" prop="unit" align="center"></el-table-column>
          <template v-if="hasFeedback || hasClose">
            <el-table-column label="是否满足现场要求" width="110" align="center">
              <template slot-scope="scope">
                <el-switch
                  :disabled="scope.row.switchDisabled"
                  :value="scope.row.finishFlag"
                  @change="(v) => handleSwitchChange(v, scope.row, scope['$index'])"
                  active-value="1"
                  inactive-value="0"
                  active-text="是"
                  inactive-text="否"
                  active-color="#13ce66"
                  inactive-color="#ff4949">
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column label="备注" width="160" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-input
                  v-if="scope.row.hasEdit"
                  placeholder="备注"
                  type="text"
                  :value="scope.row.remark"
                  @input="(v) => handleRemarkChange(v, scope.row, scope['$index'])">
                </el-input>
                <span v-else> {{ scope.row.remark }} </span>
              </template>
            </el-table-column>
          </template>
          <el-table-column label="计划进场时间" prop="planApproachDate" align="center"></el-table-column>
          <el-table-column label="附件" v-if="hasFeedback || hasClose" prop="fileUrl" align="center" width="150">
            <template slot-scope="scope">
              <div class="file-text" v-if="scope.row.fileUrl">
                <el-image
                  v-if="/\.jpg|\.jpeg|\.png$/.test(scope.row.fileUrl)"
                  class="img"
                  :src="$checkUrl(scope.row.fileUrl)"
                  :preview-src-list="[$checkUrl(scope.row.fileUrl)]">
                </el-image>
                <span
                  v-else
                  class="file-name"
                  :title="files(scope.row.fileUrl).name"
                  @click="handleUpload(scope.row.fileUrl)">
                  {{ files(scope.row.fileUrl).name }}
                </span>
                <i v-if="scope.row.fileUrl" class="el-icon-delete file-delete" @click="handleRemove(scope.row.fileUrl, scope['$index'])"></i>
              </div>
              <el-upload
                v-else-if="scope.row.hasEdit"
                :class="scope.row.hasEdit ? '' : 'file-disable'"
                :disabled="!scope.row.hasEdit"
                ref="upload"
                :limit="1"
                action="#"
                :multiple="false"
                :on-change="(file) => handleDownLoad(file, scope.row, scope['$index'])"
                :file-list="scope.row.files"
                :auto-upload="false">
                <el-button
                  :disabled="!scope.row.hasEdit"
                  slot="trigger"
                  :loading="scope.row.loading"
                  size="small"
                  type="primary">
                  选取文件
                </el-button>
              </el-upload>
            </template>
          </el-table-column>
          <div class="empty-content" slot="empty">
            <i class="iconfont iconwushuju"></i>
            <p>暂无数据</p>
          </div>
        </el-table>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item v-if="hasCheck" label="是否同意该计划" prop="agree" required>
            <el-switch
              v-model="ruleForm.agree"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </el-form-item>
          <el-form-item v-else label="审核人员" prop="reviewUser" required>
            <span class="detail-text" v-if="hasDetail">{{ ruleForm.reviewName || '' }}</span>
            <el-select
              v-else
              placeholder="请选择审核人员"
              clearable
              filterable
              v-model="ruleForm.reviewUser">
              <el-option
                v-for="v in userList"
                :label="v.userName"
                :value="v.uuid"
                :key="v.uuid">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="timeLabel" prop="writeTime" required>
            <span class="detail-text" v-if="hasDetail || hasCheck">{{ ruleForm.writeTime || '' }}</span>
            <el-date-picker
              v-else
              v-model="ruleForm.writeTime"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="请选择时间">
            </el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="12" v-if="hasDetail && ruleForm.status === '3'">
          <el-form-item label="原因" prop="reason">
            <span class="detail-text">{{ruleForm.reason}}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-else-if="!ruleForm.agree && hasCheck">
          <el-form-item label="说明原因" prop="reason">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入原因"
              v-model="ruleForm.reason">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="!hasCheck">
        <el-col :span="12">
          <el-form-item label="抄送人员" prop="copyUser">
            <span class="detail-text" v-if="hasDetail">{{ ruleForm.copyUserName || '' }}</span>
            <el-select
              v-else
              placeholder="请选择抄送人员"
              clearable
              filterable
              v-model="ruleForm.copyUser">
              <el-option
                v-for="v in userList"
                :label="v.userName"
                :value="v.uuid"
                :key="v.uuid">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-dialog
      class="add-plan-table"
      title="材料设置"
      :close-on-click-modal="false"
      :append-to-body="true"
      :destroy-on-close="true"
      :visible="addVisible"
      :width="$setRem(600)"
      :before-close="beforeClose">
      <el-form
        element-loading-custom-class="custom-load"
        :model="addForm"
        :rules="addRules"
        size="medium"
        ref="addForm"
        :label-width="$setRem(140)"
        class="rule-form"
      >
        <el-form-item label="名称" prop="materialName" required>
          <el-input
            type="text"
            clearable
            placeholder="请输入名称"
            v-model="addForm.materialName">
          </el-input>
        </el-form-item>
        <el-form-item label="规格/型号" prop="specs" required>
          <el-input
            type="text"
            clearable
            placeholder="请输入规格/型号"
            v-model="addForm.specs">
          </el-input>
        </el-form-item>
        <el-form-item label="单位" prop="unit" required>
          <el-input
            type="text"
            clearable
            placeholder="请输入单位"
            v-model="addForm.unit">
          </el-input>
        </el-form-item>
        <el-form-item label="数量" prop="planNum" required>
          <el-input-number
            :min="0"
            clearable
            placeholder="请输入数量"
            v-model="addForm.planNum">
          </el-input-number>
        </el-form-item>
        <el-form-item label="计划进场时间" prop="planApproachDate" required>
          <el-date-picker
            v-model="addForm.planApproachDate"
            format="yyyy-MM-d"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="请选择上传时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="addVisible = false">取 消</el-button>
        <el-button
          size="medium"
          type="primary"
          @click="hanldeSubmit">
          保 存
        </el-button>
      </span>
    </el-dialog>
    <span slot="footer" class="dialog-footer">
      <el-button
        size="medium"
        type="primary"
        v-if="!hasDetail"
        @click="hanldeSave('2')">
        提 交
      </el-button>
      <el-button
        size="medium"
        type="primary"
        v-if="hasAdd || hasEdit"
        @click="hanldeSave('1')">
        暂 存
      </el-button>
      <el-button size="medium" @click="handleCancel">取 消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import InputName from '@/components/public/InputName';

export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    id: {
      type: String,
      default: ''
    },
    type: {
      type: String,
      default: 'add'
    },
    options: {
      type: Object,
      default: () => ({})
    },
    status: {
      type: String,
      default: ''
    },
  },
  data() {
    return {
      userList: [],
      tableData: [],
      // 审核反馈计划列表
      planList: [],
      tableLoading: false,
      ruleForm: {
        id: '',
        planName: '',
        planNo: '',
        reviewUser: '',
        reviewName: '',
        status: '',
        agree: true,
        reason: '',
        copyUser: '',
        writeTime: this.$moment().format('YYYY-MM-DD')
      },
      rules: {
        planName: [
          { required: true, message: '请输入计划名称' },
        ],
        planNo: [
          { required: true, message: '请输入计划编号' },
        ],
        reviewUser: [
          { required: true, message: '请选择审核人员' },
        ],
        writeTime: [
          { required: true, message: '请选择时间' },
        ],
      },
      addVisible: false,
      addForm: {
        materialName: '',
        specs: '',
        unit: '',
        planNum: '',
        planApproachDate: ''
      },
      addRules: {
        materialName: [
          { required: true, message: '请输入名称' },
          { trigger: 'blur' },
        ],
        specs: [
          { required: true, message: '请输入规格/型号' },
          { trigger: 'blur' },
        ],
        unit: [
          { required: true, message: '请输入单位' },
          { trigger: 'blur' },
        ],
        planNum: [
          { required: true, message: '请输入数量' },
        ],
        planApproachDate: [
          { required: true, message: '请输入计划进场时间' },
        ],
      },
      detailData: {},
      activeIndex: ''
    };
  },
  computed: {
    width() {
      return['feedback', 'close'].includes(this.type)
        ? this.$setRem(1400)
        : this.$setRem(900);
    },
    title() {
      if (this.hasAdd) return '新增材料计划';
      if (this.hasEdit) return '编辑材料计划';
      if (this.hasFeedback) return '反馈';
      if (this.hasClose) return '闭合';
      else return '审核';
    },
    projectId() {
      return this.$store.state.currentProjectId;
    },
    userInfo() {
      return this.$store.state.userInfo;
    },
    currentData() {
      return this.activeIndex ? this.tableData[this.activeIndex] : {};
    },
    // 新增
    hasAdd() {
      return this.type === 'add';
    },
    // 编辑
    hasEdit() {
      return this.type === 'edit';
    },
    hasDetail() {
      return this.type === 'detail';
    },
    // 审核
    hasCheck() {
      return this.type === 'check';
    },
    // 反馈
    hasFeedback() {
      return this.type === 'feedback';
    },
    // 闭合
    hasClose() {
      return this.type === 'close';
    },
    timeLabel() {
      if (this.hasCheck) return '审核时间';
      if (this.hasClose) return '闭合时间';
      if (this.hasFeedback) return '反馈时间';
      return '填写时间';
    }
  },
  watch: {
    options: {
      deep: true,
      handler(data) {
        if (data) {
          const keys = Object.keys(this.ruleForm);
          Object.keys(data).length && keys.forEach(key => {
            const value = data[key] || '';
            this.ruleForm[key] = key === 'agree' ? true : value;
          });
          let list = data.materialPlanDetails || [];
          // 反馈和关闭
          if (this.hasFeedback || this.hasClose) {
            // 过滤已闭合的材料 closeFlag: 0：未闭合；1：已闭合
            list = list
              .filter(item => item.closeFlag !== '1')
              .map(item => {
                // 当累计数量≥计划数量时，自动闭合 显示“是”
                const { planNum, totalNum } = item;
                // finishFlag 是否满足需求(0：不满足；1：满足)
                const total = isNaN(totalNum) ? 0 : Number(totalNum);
                // 是否开启
                const hasOpen = total >= planNum;
                const switchDisabled = this.hasFeedback;
                const hasEdit = this.hasFeedback ? false : hasOpen;
                return {
                  ...item,
                  hasCheck: false,
                  currentNum: '',
                  finishFlag: hasOpen ? '1' : '0',
                  switchDisabled,
                  hasEdit,
                  remark: '',
                  fileUrl: '',
                  files: []
                };
              });
          } else {
            list = list.map(item => {
              return {
                ...item,
                switchDisabled: true,
                hasEdit: false,
                hasCheck: false,
              };
            });
          }
          this.tableData = list;
        }
      }
    },
    visible(val) {
      if (!val) {
        this.ruleForm = {
          id: '',
          planName: '',
          planNo: '',
          reviewUser: '',
          reviewName: '',
          status: '',
          agree: true,
          reason: '',
          copyUser: '',
          writeTime: this.$moment().format('YYYY-MM-DD')
        };
        this.tableLoading = false;
        this.activeIndex = '';
      }
    },
    type(val) {
      if (val === 'add') this.getMaterialPlanNo();
    }
  },
  created() {
    this.getUserList();
  },
  components: {
    InputName
  },
  methods: {
    // 获取计划编号
    async getMaterialPlanNo() {
      const { success, data: { data }} = await this.$Model.getMaterialPlanNo();
      if (success && data) {
        this.ruleForm.planNo = data;
      }
    },
    /**
     * 获取用户列表数据
     */
    async getUserList() {
      const params = {
        pageFlag: false
      };
      const { success, data: {
        data
      }} = await this.$Model.getUserList(params);
      if (success && data) {
        this.userList = data.list || [];
      }
    },
    handleSelect(row, index) {
      const hasCurrent = this.activeIndex === index;
      this.activeIndex = hasCurrent ? '' : index;
      this.tableData = this.tableData.map((item, i) => ({
        ...item,
        hasCheck: hasCurrent ? false : i === index
      }));
    },
    // 本次到场数量修改
    handleChange(value, row, index) {
      const { planNum, totalNum } = row;
      const item = { ...this.tableData[index] };
      item.currentNum = value === 0 ? value : value || '';
      item.switchDisabled = false;
      item.hasEdit = true;
      const total = isNaN(totalNum)
        ? Number(item.currentNum)
        : Number(item.currentNum) + Number(totalNum);
      item.finishFlag = total >= planNum ? '1' : '0';
      if (value !== 0 && !value) {
        item.remark = '';
        item.switchDisabled = true;
        item.hasEdit = false;
      }
      this.tableData.splice(index, 1, item);
      return true;
    },
    // 是否满足现场要求
    handleSwitchChange(val, row, index) {
      const item = { ...this.tableData[index] };
      item.finishFlag = val;
      if (this.hasClose) {
        item.hasEdit = val === '1';
      }
      this.tableData.splice(index, 1, item);
    },
    // 修改材料备注
    handleRemarkChange(val, row, index) {
      const item = this.tableData[index];
      item.remark = val || '';
      // this.tableData.splice(index, 1, item);
    },
    // 附件
    files(fileUrl) {
      const fileNames = fileUrl ? fileUrl.match(/([^\/])+\.\w+$/) : '';
      const fileName = Array.isArray(fileNames) ? fileNames[0] : '';
      return {
        name: fileName,
        url: this.$checkUrl(fileUrl),
        hasImg: /\.jpg|\.jpeg|\.png$/.test(fileUrl)
      };
    },
    /**
     * 选取文件
     */
    handleDownLoad(file, row, index) {
      this.fileUpload(file.raw, row, index);
      return false;
    },
    // 上传文件
    async fileUpload(file, row, index) {
      const item = this.tableData[index];
      const fm = new FormData();
      fm.append('file', file);
      item.loading = true;
      const { success, data: { data }} = await this.$Model.fileUpload(fm);
      item.loading = false;
      if (success && data) {
        item.files = [{
          name: file.name,
          url: data
        }];
        item.fileUrl = data;
      }
    },
    /**
     * 删除文件
     */
    async handleRemove(fileUrl, index) {
      const { success } = await this.$Model.fileDelete({ filePath: fileUrl });
      const item = this.tableData[index];
      if (success) {
        item.files = [];
        item.fileUrl = '';
      }
    },
    // 下载文件
    handleUpload(fileUrl) {
      fileUrl && window.open(this.$checkUrl(fileUrl));
    },
    // 新增材料
    handleAdd() {
      this.addForm = {
        materialName: '',
        specs: '',
        unit: '',
        planNum: '',
        planApproachDate: ''
      };
      this.addVisible = true;
    },
    handleDelete() {
      if (this.activeIndex !== 0 && !this.activeIndex) return;
      this.tableData.splice(this.activeIndex, 1);
      this.activeIndex = '';
    },
    beforeClose() {
      this.addVisible = false;
    },
    handleCancel() {
      this.$emit('cancel');
    },
    hanldeSubmit() {
      this.$refs.addForm.validate(async valid => {
        if (valid) {
          this.tableData.push({
            ...this.addForm,
            hasCheck: false
          });
          this.addVisible = false;
        }
      });
    },
    // 保存
    hanldeSave(status) {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const { userName, uuid } = this.userInfo;
          const { reviewUser, agree, reviewName, copyUser } = this.ruleForm;
          const createUser = this.options && this.options.createUser || uuid;
          // 审核人信息
          const reviewUserItem = this.userList.find(v => {
            return v.uuid === reviewUser;
          }) || {};
          // 抄送人信息
          const copyUserItem = this.userList.find(v => {
            return v.uuid === copyUser;
          }) || {};
          // 创建人信息
          const createUserItem = this.userList.find(v => {
            return v.uuid === createUser;
          }) || {};
          const createUserName = createUserItem.userName || userName;
          const reviewUserName = reviewUserItem.userName || reviewName || '';
          const copyUserName = copyUserItem.userName || '';
          let checkStatus = '';
          if (this.hasFeedback) checkStatus = '4';
          else if (this.hasClose) checkStatus = '5';
          const params = {
            ...this.ruleForm,
            // 是否已读（0：未读；1：已读）
            readFlag: '0',
            projectId: this.projectId,
            // 1：暂存；2：审核中；3：已退回；4：反馈中；5：闭合）
            status: !agree
              ? '3'
              : this.hasCheck ? '4' : checkStatus || status,
            createUserName,
            createUser,
            reviewUserName,
            copyUserName,
            materialPlanDetails: this.tableData
          };
          this.$emit('submit', params);
        }
      });
    },
  }
};
</script>

<style scoped lang="scss">
  @import "../../../assets/styles/table";
  @import "../../../assets/styles/dialog";
  .material-add-plan-comp {
    .btns {
      margin: 10px 0;
      width: 100%;
      text-align: right;
    }
    /deep/ .el-form-item__content {
      min-width: 240px;
      max-width: 400px;
    }
    .table-container {
      margin: 20px 0;
      width: 100%;
      /deep/ .el-table__body-wrapper {
        min-height: 200px;
        max-height: 350px;
        overflow-y: auto;
        .file-text {
          max-width: 150px;
          display: flex;
          align-items: center;
          justify-content: flex-start;
          padding-right: 20px;
          .file-name {
            max-width: 130px;
            display: inline-block;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            position: relative;
          }
          .img {
            width: 100px;
            height: 65px;
          }
          i.file-delete {
            font-size: 16px;
            color: $mainColor;
            cursor: pointer;
          }
        }
      }
    }
    .file-disable {
      /deep/ .el-upload {
        .el-button {
          span {
            color: #fff;
          }
        }
      }
    }
  }
  .add-plan-table {
    /deep/ .el-form-item {
      .el-form-item__label {
        color: #fff;
      }
      .el-form-item__content {
        width: 300px;
      }
    }
  }
</style>
